<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="优惠卷名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入优惠卷名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['sale:coupon:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['sale:coupon:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['sale:coupon:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['sale:coupon:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <!-- ；0-&gt;全场赠券；2-&gt;购物赠券； -->
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          {{ scope.row.type == 1 ? '全场赠券' : scope.row.type == 2 ? '购物赠券' : '无' }}
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="面值" align="center" prop="amount"/>
      <el-table-column label="使用门槛" align="center" prop="minPoint"/>
      <el-table-column label="使用类型" align="center" prop="useType">
        <template #default="scope">{{
            scope.row.useType == 1 ? '全场通用' : scope.row.useType == 2 ? '指定分类' :
              scope.row.useType == 3 ? '指定商品' : '无'
          }}
        </template>
      </el-table-column>
      <el-table-column label="发行数量" align="center" prop="publishCount"/>
      <el-table-column label="可以领取的日期" align="center" prop="enableTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.enableTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['sale:coupon:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['sale:coupon:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-row :gutter="20">
          <el-col :span="12">
            <!--  /** 优惠券类型；0-&gt;全场赠券；2-&gt;购物赠券； */ -->
            <el-form-item label="优惠卷名称" prop="type">
              <el-select v-model="form.type" clearable placeholder="请选择优惠券类型">
                <el-option :value="1" label="全场赠券">全场赠券</el-option>
                <el-option :value="2" label="购物赠券">购物赠券</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可以领取的日期" prop="enableTime">
              <el-date-picker clearable v-model="form.enableTime" type="date" value-format="yyyy-MM-dd"
                              placeholder="请选择可以领取的日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入金额">
                <slot slot="append">元</slot>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每人限领张数" prop="perLimit">
              <el-input v-model="form.perLimit" placeholder="请输入每人限领张数"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用门槛" prop="minPoint">
              <el-input v-model="form.minPoint" placeholder="请输入使用门槛；0表示无门槛">
                <slot slot="append">元</slot>
                <slot slot="prepend">满</slot>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
                              placeholder="请选择开始时间"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">

              <el-date-picker clearable v-model="form.endTime" type="date" value-format="yyyy-MM-dd"
                              placeholder="请选择结束时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="note">
              <el-input v-model="form.note" type="textarea" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发行数量" prop="publishCount">
              <el-input v-model="form.publishCount" placeholder="请输入发行数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠卷名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入优惠卷名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="可使用商品" prop="useCount">
            <el-button :class="{'tab-active':tagNumber==0}" @click="handleTab(0)">全场通用</el-button>
            <el-button :class="{'tab-active':tagNumber==1}" @click="handleTab(1)">指定地州</el-button>
            <el-button :class="{'tab-active':tagNumber==2}" @click="handleTab(2)">指定商品</el-button>

          </el-form-item>
          <el-form-item>
            <div v-if="tagNumber==1">
              <el-select v-model="regionId" clearable placeholder="请选择">
                <el-option v-for="item in regionList" :key="item.id" :label="item.name" :value="item.id">{{
                    item.name
                  }}
                </el-option>
              </el-select>
              <el-button @click="addRegionOfTable">添加</el-button>
              <el-table :data="regionData" border style="width: 100%">
                <el-table-column prop="id" label="编号" align="center" width="60px"/>
                <el-table-column prop="name" label="地区名称" align="center"/>
                <el-table-column label="操作" width="60px">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleDeleteRegion(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>


            <div v-if="tagNumber==2">
              <el-autocomplete v-model="productName" :fetch-suggestions="getProductNames" placeholder="请输入名称"
                               @select="handleSelect" clearable></el-autocomplete>

              <el-button @click="addProductOfTable">添加</el-button>
              <el-table :data="productData" border style="width: 100%">
                <el-table-column prop="id" label="编号" align="center" width="60px"/>
                <el-table-column prop="name" label="商品名称" align="center"/>
                <el-table-column label="操作" width="60px">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleDeleteProduct(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon} from "@/api/sale/coupon";
import {getBrandName, getRegionName, getProductNames} from "@/api/common/common";

export default {
  name: "Coupon",
  data() {
    return {
      regionId: "",
      regionList: [],
      ProductNameList: [],
      productName: "",
      productId: "",
      tagNumber: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        name: null,
      },
      // 表单参数
      form: {
        useType: 0
      },
      // 表单校验
      rules: {
        type: [{required: true, message: '选择优惠卷类型', trigger: 'change'}],
        amount: [{required: true, message: '请输入金额', trigger: 'blur'}],
        name: [{required: true, message: '请输入优惠卷名称', trigger: 'blur'}],
        perLimit: [{required: true, message: '请输入每人限领张数', trigger: 'blur'}],
        minPoint: [{required: true, message: '请输入使用门槛', trigger: 'blur'}],
        startTime: [{required: true, message: '请选择开始时间', trigger: 'change'}],
        endTime: [{required: true, message: '请选择结束时间', trigger: 'change'}],
        publishCount: [{required: true, message: '请输入发行数量', trigger: 'blur'}],
        enableTime: [{required: true, message: '请选择可以领取的日期', trigger: 'change'}],
      },
      regionData: [],
      productData: []
    };
  },
  created() {
    this.getList();
  },
  computed: {},
  methods: {
    async getProductNames(queryString, cb) {
      if (queryString === '') {
        cb([]);
        return;
      }
      try {
        const response = await getProductNames(queryString)
        const results = response.data.map(item => ({
          value: item.name,
          id: item.id
        }));
        cb(results);
      } catch (error) {
        console.error('请求失败:', error);
        cb([]);
      }
    },
    handleSelect(item) {
      this.productName = item.value;
      this.productId = item.id
    },
    addProductOfTable() {
      if (this.productName == "") return this.$message.error('请输入商品名称')
      if (this.productData.some(item => item.name == this.productName)) return this.$message.error('已存在')
      this.productData.push({
        id: this.productId,
        name: this.productName
      })
    },
    addRegionOfTable() {
      if (this.regionId == "") return this.$message.error('请输入地州')
      //判断是否存在
      if (this.regionData.some(item => item.id == this.regionId)) return this.$message.error('已存在')
      this.regionList.forEach(item => {
        if (item.id == this.regionId) {
          this.regionData.push({
            id: item.id,
            name: item.name
          })
        }
      })
    },
    handleDeleteProduct(row) {
      this.productData.forEach((item, index) => {
        if (item.id == row.id) {
          this.productData.splice(index, 1)
        }
      })
    },
    handleDeleteRegion(row) {
      this.regionData.forEach((item, index) => {
        if (item.id == row.id) {
          this.regionData.splice(index, 1)
        }
      })
    },
    getRegionName() {
      getRegionName().then(res => {
        this.regionList = res.data
      })
    },
    handleTab(number) {
      this.tagNumber = number
      this.form.useType = number
    },
    /** 查询优惠券列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        name: null,
        count: null,
        amount: null,
        perLimit: null,
        minPoint: null,
        startTime: null,
        endTime: null,
        useType: null,
        note: null,
        publishCount: null,
        useCount: null,
        receiveCount: null,
        enableTime: null,
        code: null,
        memberLevel: null
      };
      this.regionData = []
      this.productData = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getRegionName()
      this.reset();
      this.tagNumber = 0
      this.open = true;
      this.title = "添加优惠券";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getRegionName()
      this.reset();
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.form = response.data;
        this.tagNumber = response.data.useType
        if (response.data.useType == 1) {//地州回显
          // this.regionData.push({})
          response.data.regionRelations.forEach(item => {
            this.regionData.push({
              id: item.regionId,
              name: item.regionName,
              regionRelationId: item.id
            })
          })
        } else if (response.data.useType == 2) {
          response.data.productRelations.forEach(item => {
            this.productData.push({
              id: item.productId,
              name: item.productName,
              productRelationId: item.id
            })
          })
        }
        this.open = true;
        this.title = "修改优惠券";
      });
    },
    //处理数据
    handleData() {

    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form)
      if (this.form.useType == 1) {
        if (this.regionData.length == 0) return this.$message.error('请选择地州')
      } else if (this.form.useType == 2) {
        if (this.productData.length == 0) return this.$message.error('请选择商品')
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            console.log("进入修改")
            this.form.regionRelations = []
            this.form.productRelations = []
            if (this.regionData.length != 0) {
              let regionRelations = []
              this.regionData.forEach(item => {
                regionRelations.push({
                  id: item.regionRelationId,
                  regionId: item.id,
                  regionName: item.name
                })
              })
              this.form.regionRelations = regionRelations
            }
            if (this.productData.length != 0) {
              let productRelations = []
              this.productData.forEach(item => {
                productRelations.push({
                  id: item.productRelationId,
                  productId: item.id,
                  productName: item.name
                })
              })
              this.form.productRelations = productRelations
            }

            console.log(this.form)
            updateCoupon(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          } else {
            //处理数据
            if (this.regionData.length != 0) {
              let regionRelations = []
              this.regionData.forEach(item => {
                regionRelations.push({
                  regionId: item.id,
                  regionName: item.name
                })
              })
              this.form.regionRelations = regionRelations
            }
            if (this.productData.length != 0) {
              let productRelations = []
              this.productData.forEach(item => {
                productRelations.push({
                  productId: item.id,
                  productName: item.name
                })
              })
              this.form.productRelations = productRelations
            }
            if (!this.form.useType) {
              this.form.useType = 0
            }
            addCoupon(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          }

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除优惠券编号为"' + ids + '"的数据项？').then(function () {
        return delCoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sale/coupon/export', {
        ...this.queryParams
      }, `coupon_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.tab-active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}
</style>
